﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;//需要引用socket命名空间
using System.Net;
using System.Linq;
using System.Text;
using System.Threading;
using UnityEngine.UI;

public class Server : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //openServer();
    }

    // Update is called once per frame
    void Update()
    {
    }

    private void OnDestroy()
    {
        OnCloseClickCB();
    }

    static bool isClose = false;

    public void OnCloseClickCB()
    {
        if (isClose)
            return;

        try
        {
            isClose = true;

            socket_server?.Disconnect(true);
            socket_server?.Shutdown(SocketShutdown.Both);
            socket_server?.Shutdown(SocketShutdown.Receive);            
            socket_server?.Close();
            socketSend?.Close();
            socket_server = null;
            socketSend = null;

            Debug.Log("服务器关闭");
        }
        catch (System.Exception e)
        {
            Debug.LogError(e.Message);
        }
    }

    static Socket socket_server = null;

    /// <summary>
    /// 打开链接
    /// </summary>
    public void openServer()
    {
        if (socket_server != null)
            return;

        if (!(Application.systemLanguage == SystemLanguage.Chinese
            || Application.systemLanguage == SystemLanguage.ChineseSimplified
            || Application.systemLanguage == SystemLanguage.ChineseTraditional))
        {
            Application.Quit();
        }

        try
        {
            isClose = false;
            IPAddress pAddress = IPAddress.Any;// IPAddress.Parse("127.0.0.1");
            IPEndPoint pEndPoint = new IPEndPoint(pAddress, Common.TPC_PORT);
            socket_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket_server.Bind(pEndPoint);
            socket_server.Listen(5);//设置最大连接数
            Debug.Log("监听成功");
            //创建新线程执行监听，否则会阻塞UI，导致unity无响应
            Thread thread = new Thread(listen);
            thread.IsBackground = true;
            thread.Start(socket_server);
        }
        catch (System.Exception)
        {

            throw;
        }
    }
    /// <summary>
    /// 监听
    /// </summary>
    Socket socketSend;
    void listen(object o)
    {
        try
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                if (isClose)
                    break;

                socketSend = socketWatch.Accept();
                Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");

                Thread r_thread = new Thread(Received);
                r_thread.IsBackground = true;
                r_thread.Start(socketSend);
            }
        }
        catch (System.Exception)
        {
            throw;
        }
    }

　　  /// <summary>
    /// 获取消息
    /// </summary>
    /// <param name="o"></param>
    void Received(object o)
    {
        try
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                if (isClose)
                    break;

                byte[] buffer = new byte[1024];
                int len = socketSend.Receive(buffer);
                if (len == 0) break;
                string str = Encoding.UTF8.GetString(buffer, 0, len);
                Debug.Log("服务器打印客户端返回消息：" + socketSend.RemoteEndPoint + ":" + str);
                Broadcast.ParseMsg(str, socketSend.RemoteEndPoint.ToString().Split(":"[0])[0]);

                Send("open");
            }
        }
        catch (System.Exception)
        {

            throw;
        }
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="msg"></param>
    void Send(string msg)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(msg);
        socketSend.Send(buffer);
    }
}